package com.controller;

import com.alibaba.fastjson.JSON;
import com.entity.Working;
import com.service.WorkingService;
import com.util.Pager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.List;

@Controller
public class WorkingController {
    SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-context.xml");
    WorkingService service = (WorkingService) ctx.getBean("workingService");

    @RequestMapping("/home")
    public String workingList(Integer pageIndex, Model m){

        pageIndex=pageIndex==null ? 1:pageIndex;
        List<Working> list = service.getAllWorking((pageIndex-1)*5);
        Pager pager = new Pager(service.count(),5,pageIndex);

        m.addAttribute("list",list);
        m.addAttribute("totalPageCount", pager.getPageCount());
        m.addAttribute("totalCount", pager.getRowCount());
        m.addAttribute("currentPageNo", pager.getCurrentPage());

        return "home";
    }

    @RequestMapping("/add")
    public String workingAdd(){
        return "add";
    }

    @RequestMapping("/addsave")
    public String workingAdd(Working working){
        if (service.insert(working)>0){
            return "redirect:/home";
        }
        return "error";
    }


    @RequestMapping("/get")
    public String workingGet(Integer id, Model m){
        Working working = service.getWorking(id);
        m.addAttribute("w",working);
        return "get";
    }

    @RequestMapping(value = "/titleGet",method=RequestMethod.POST)
    @ResponseBody
    public Object getTitle(String title, Model m){
        boolean back = service.getTitleCount(title)>0;
        return JSON.toJSONString(back);
    }

    @RequestMapping("/up")
    public String workingUpdate(Integer id, Model m){
        Working working = service.getWorking(id);
        m.addAttribute("w",working);
        return "update";
    }

    @RequestMapping("/update")
    public String workingUpdate(Working working, Model m){
        if (service.update(working)>0){
            m.addAttribute("w",working);
            return "redirect:/home";
        }
        return "error";
    }

    @RequestMapping("/del")
    public String workingDel(Integer id, Model m){
        if (service.delete(id)>0){
            return "redirect:/home";
        }
        return "error";
    }


}
